/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 *
 * @format
 */

"use strict";
let transform = (() => {
  var _ref2 = _asyncToGenerator(function*(
    filename,
    transformOptions,
    projectRootArg,
    transformerConfig
  ) {
    if (!projectRoot) {
      setup(projectRootArg, transformerConfig);
    }

    const transformFileStartLogEntry = {
      action_name: "Transforming file",
      action_phase: "start",
      file_name: filename,
      log_entry_label: "Transforming file",
      start_timestamp: process.hrtime()
    };

    const data = fs.readFileSync(path.resolve(projectRoot, filename));
    const sha1 = crypto
      .createHash("sha1")
      .update(data)
      .digest("hex");

    const result = yield transformer.transform(
      filename,
      data,
      transformOptions
    );

    const transformFileEndLogEntry = getEndLogEntry(
      transformFileStartLogEntry,
      filename
    );

    return {
      result,
      sha1,
      transformFileStartLogEntry,
      transformFileEndLogEntry
    };
  });
  return function transform(_x, _x2, _x3, _x4) {
    return _ref2.apply(this, arguments);
  };
})();
function _asyncToGenerator(fn) {
  return function() {
    var gen = fn.apply(this, arguments);
    return new Promise(function(resolve, reject) {
      function step(key, arg) {
        try {
          var info = gen[key](arg);
          var value = info.value;
        } catch (error) {
          reject(error);
          return;
        }
        if (info.done) {
          resolve(value);
        } else {
          return Promise.resolve(value).then(
            function(value) {
              step("next", value);
            },
            function(err) {
              step("throw", err);
            }
          );
        }
      }
      return step("next");
    });
  };
}
const crypto = require("crypto");
const fs = require("fs");
const path = require("path");
let transformer;
let projectRoot;
function setup(projectRootArg, _ref) {
  let transformerPath = _ref.transformerPath,
    transformerConfig = _ref.transformerConfig; // eslint-disable-next-line lint/flow-no-fixme
  // $FlowFixMe Transforming fixed types to generic types during refactor.
  const Transformer = require(transformerPath);
  projectRoot = projectRootArg;
  transformer = new Transformer(projectRoot, transformerConfig);
}
function getEndLogEntry(startLogEntry, filename) {
  const timeDelta = process.hrtime(startLogEntry.start_timestamp);
  const duration_ms = Math.round((timeDelta[0] * 1e9 + timeDelta[1]) / 1e6);

  return {
    action_name: "Transforming file",
    action_phase: "end",
    file_name: filename,
    duration_ms,
    log_entry_label: "Transforming file"
  };
}

module.exports = {
  setup,
  transform
};
